package com.wuhao.shootclient.util;

import android.os.CountDownTimer;

import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

/**
 * Create by hao on 2020/8/4
 */
public class MyCountDownTimer extends CountDownTimer {

    public static final String CLASS_TAG = "MyCountDownTimer";
    public static Lock mLock = new ReentrantLock();
    public CountDownCallback mCountDownCallback;
    public static MyCountDownTimer ins;

    public static MyCountDownTimer getIns(long millisInFuture, long countDownInterval, CountDownCallback countDownCallback) {
        if (mLock.tryLock()) {
            try {
                if (ins == null) {
                    ins = new MyCountDownTimer(millisInFuture, countDownInterval, countDownCallback);
                }
            } catch (Exception e) {
                LogUtil.error("exception:" + e);
            } finally {
                mLock.unlock();
                LogUtil.error("mLock.unlock()");
            }
        }
        LogUtil.error("ins:" + ins);
        return ins;
    }

    /**
     * @param millisInFuture    The number of millis in the future from the call
     *                          to {@link #start()} until the countdown is done and {@link #onFinish()}
     *                          is called.
     * @param countDownInterval The interval along the way to receive
     *                          {@link #onTick(long)} callbacks.
     */
    public MyCountDownTimer(long millisInFuture, long countDownInterval, CountDownCallback countDownCallback) {
        super(millisInFuture, countDownInterval);
        mCountDownCallback = countDownCallback;
        mCountDownCallback.startCountDown(millisInFuture);
    }

    @Override
    public void onTick(long millisUntilFinished) {
        mCountDownCallback.onCountDown(millisUntilFinished);
    }

    @Override
    public void onFinish() {
        mCountDownCallback.endCountDown();
    }

     public interface CountDownCallback {
        void startCountDown(long millisInFuture);

        void onCountDown(long millisUntilFinished);

        void endCountDown();
    }
}